package com.lxy.demo.session;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "TestSessionServlet", urlPatterns = "/TestSessionServlet")
public class TestSessionServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //1.创建session对象
        HttpSession session = request.getSession();
        //2.设置session存活时间(秒) 默认半小时
        session.setMaxInactiveInterval(30*60);
        //3.把sessionId响应到页面
        response.getWriter().write(session.getId());

        //延长session存活时间 让浏览器关闭，session依然存在
        Cookie cookie = new Cookie("JSESSIONID", session.getId());
        System.out.println(session.getId());
        cookie.setPath(request.getContextPath());
        cookie.setMaxAge(3*60);
        response.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
